<!-- src/views/teacher/UserProfile.vue -->
<template>
  <div class="user-profile">
    <div class="header">
      <el-page-header @back="$router.go(-1)" title="返回">
        <template #content>
          <span class="title">个人信息</span>
        </template>
      </el-page-header>
    </div>

    <el-row :gutter="20">
      <el-col :span="16">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>基本信息</span>
            </div>
          </template>

          <el-form
            :model="profileForm"
            :rules="profileRules"
            ref="profileFormRef"
            label-width="100px"
          >
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="工号" prop="employeeNumber">
                  <el-input v-model="profileForm.employeeNumber" disabled />
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="姓名" prop="name">
                  <el-input v-model="profileForm.name" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="性别" prop="gender">
                  <el-select v-model="profileForm.gender" style="width: 100%">
                    <el-option label="男" :value="1" />
                    <el-option label="女" :value="2" />
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="所属院系" prop="department">
                  <el-input v-model="profileForm.department" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="职称" prop="title">
                  <el-input v-model="profileForm.title" />
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="联系电话" prop="phone">
                  <el-input v-model="profileForm.phone" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="邮箱" prop="email">
                  <el-input v-model="profileForm.email" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-form-item>
              <el-button
                type="primary"
                @click="updateProfile"
                :loading="saveLoading"
              >
                保存信息
              </el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>

      <el-col :span="8">
        <el-card class="avatar-card">
          <template #header>
            <div class="card-header">
              <span>头像</span>
            </div>
          </template>

          <div class="avatar-container">
            <el-avatar
              :size="100"
              :src="profileForm.avatar || defaultAvatar"
              class="avatar"
            />

            <div class="avatar-actions">
              <el-upload
                class="avatar-uploader"
                action="/api/upload/avatar"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :on-error="handleAvatarError"
              >
                <el-button size="small" type="primary">上传头像</el-button>
              </el-upload>

              <el-button
                size="small"
                @click="removeAvatar"
                :disabled="!profileForm.avatar"
              >
                移除头像
              </el-button>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useTeacherStore } from '../../store/teacher'
import { ElMessage } from 'element-plus'

const teacherStore = useTeacherStore()

const saveLoading = ref(false)
const defaultAvatar = 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'

// 表单数据
const profileForm = reactive({
  employeeNumber: '',
  name: '',
  gender: null,
  department: '',
  title: '',
  phone: '',
  email: '',
  avatar: ''
})

// 表单验证规则
const profileRules = {
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  gender: [{ required: true, message: '请选择性别', trigger: 'change' }],
  department: [{ required: true, message: '请输入所属院系', trigger: 'blur' }],
  title: [{ required: true, message: '请输入职称', trigger: 'blur' }],
  phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ]
}

const profileFormRef = ref()

// 获取用户信息
const fetchProfile = async () => {
  try {
    const data = await teacherStore.getProfile()
    // 映射来自 /api/teacher/profile 接口的字段
    profileForm.employeeNumber = data.teacherNumber
    profileForm.name = data.name
    profileForm.gender = data.gender
    profileForm.department = data.department
    profileForm.title = data.title
    profileForm.avatar = data.avatar

    // 映射来自 /api/user/profile 接口的字段
    profileForm.email = data.email
    profileForm.phone = data.phone
  } catch (error) {
    ElMessage.error('获取个人信息失败: ' + (error.response?.data?.message || error.message))
  }
}

// 更新用户信息
const updateProfile = async () => {
  if (!profileFormRef.value) return

  await profileFormRef.value.validate(async (valid) => {
    if (valid) {
      saveLoading.value = true
      try {
        // 准备更新数据，将 employeeNumber 映射回 teacherNumber
        const data = {
          ...profileForm,
          teacherNumber: profileForm.employeeNumber
        }
        await teacherStore.updateProfile(data)
        ElMessage.success('信息保存成功')
      } catch (error) {
        ElMessage.error('保存失败: ' + (error.response?.data?.message || error.message))
      } finally {
        saveLoading.value = false
      }
    }
  })
}

// 头像上传成功处理
const handleAvatarSuccess = (response, file) => {
  if (response && response.data && response.data.url) {
    profileForm.avatar = response.data.url
    ElMessage.success('头像上传成功')
  } else {
    ElMessage.error('头像上传失败')
  }
}

// 头像上传失败处理
const handleAvatarError = (error) => {
  ElMessage.error('头像上传失败: ' + (error.response?.data?.message || error.message))
}

// 移除头像
const removeAvatar = () => {
  profileForm.avatar = ''
  ElMessage.success('头像已移除')
}

onMounted(() => {
  fetchProfile()
})
</script>

<style scoped>
.header {
  margin-bottom: 20px;
}

.card-header {
  font-weight: bold;
}

.avatar-container {
  text-align: center;
}

.avatar {
  margin-bottom: 20px;
}

.avatar-actions {
  display: flex;
  flex-direction: column;
  gap: 10px;
}
</style>
